<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" ref="queryForm">
      <el-form-item label="字典项名称" prop="name">
        <el-input clearable placeholder="请输入字典项名称" v-model="queryParams.name" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" icon="el-icon-search" type="primary">搜索</el-button>
        <el-button @click="handleReset" icon="el-icon-refresh">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="mb-20">
      <el-button @click="handleAdd" icon="el-icon-plus" plain type="primary">新增</el-button>
      <el-button :disabled="multiple" @click="handleDelete()" icon="el-icon-delete" plain type="danger">删除</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @selection-change="handleSelectionChange"
      border
      default-expand-all
      ref="table"
      row-key="id"
      size="mini"
      v-loading="loading"
    >
      <el-table-column type="selection" />
      <el-table-column label="字典项名称" prop="name" />
      <el-table-column label="字典项值" prop="value" />
      <!-- <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <el-switch :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row)" size="mini" v-model="scope.row.status" />
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="操作">
        <template slot-scope="{row}">
          <el-button @click.stop="handleUpdate(row)" circle icon="el-icon-edit" plain type="primary" />
          <el-button @click.stop="handleDelete(row)" circle icon="el-icon-delete" plain type="danger" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 表单弹窗 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" @close="closeDialog" width="500px">
      <el-form :model="form" :rules="rules" label-width="25%" ref="form">
        <el-form-item label="字典名称">
          <el-input :disabled="true" v-model="dict.name" />
        </el-form-item>
        <el-form-item label="字典项名称" prop="name">
          <el-input placeholder="请输入字典项名称" v-model="form.name" />
        </el-form-item>
        <el-form-item label="父级字典项" prop="parentId">
          <el-cascader
            :options="tableData"
            :props="{label:'name',value:'id',checkStrictly:true,emitPath:false}"
            clearable
            filterable
            placeholder="请选择父级字典项（选填）"
            style="width:100%"
            v-model="form.parentId"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="字典项值" prop="value">
          <el-input placeholder="请输入字典项值" v-model="form.value" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number :min="0" controls-position="right" style="width: 50%;" v-model="form.sort" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="handleSubmit" type="primary">确 定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Api from '../api'
export default {
  name: 'DictItem',
  data() {
    return {
      loading: false,
      ids: [],
      single: true,
      multiple: true,
      queryParams: {
        name: undefined,
        dictCode: undefined,
        queryMode: '1'
      },
      tableData: [],
      dialog: {
        title: undefined,
        visible: false
      },
      form: {},
      rules: {
        name: [
          { required: true, message: '请输入字典项名称', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请输入字典项值', trigger: 'blur' }
        ]
      },
      dict: {}
    }
  },
  methods: {
    handleQuery() {
      if (!this.dict.code) {
        return
      }
      this.loading = true
      Api.getDictItems(this.queryParams).then(data => {
        this.tableData = data.records
      }).finally(() => { this.loading = false })
    },
    handleReset() {
      this.queryParams = {
        name: undefined,
        dictCode: this.dict.code,
        queryMode: 'tree'
      }
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleStatusChange(row) {
      const text = row.status === 1 ? '启用' : '停用'
      this.$confirm('确认要"' + text + row.name + '"数据项吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Api.modifyLocalDictItems({ id: row.id, status: row.status }).then(() => {
          this.$message.success(text + '成功')
        })
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1
      })
    },

    handleAdd() {
      this.resetForm()
      this.dialog = {
        title: '新增字典项',
        visible: true
      }
      this.form.dictCode = this.dict.code
    },

    handleUpdate(row) {
      this.resetForm()
      this.dialog = {
        title: '修改字典项',
        visible: true
      }
      Api.getDictItemDetail(row.id).then(data => {
        this.form = data
      })
    },

    handleSubmit: function () {
      this.$refs.form.validate(valid => {
        if (valid) {
          Api.addOrUpdateDictItem({ ...this.form, level: this.level || 0 }).then(() => {
            this.$message.success(this.form.id ? '修改成功' : '新增成功')
            this.closeDialog()
            this.handleQuery()
          })
        }
      })
    },

    handleDelete(row) {
      const ids = [row.id || this.ids]
      this.$confirm('确认删除已选中的数据项？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Api.removeDictItems(ids).then(() => {
          this.$message.success('删除成功')
          this.handleQuery()
        })
      }).catch(() =>
        this.$message.info('已取消删除')
      )
    },
    closeDialog() {
      this.resetForm()
      this.dialog = {
        title: undefined,
        visible: false
      }
    },
    resetForm() {
      this.form = {}
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    dictClick(dict) {
      if (dict) {
        this.queryParams.dictCode = dict.code
        this.dict = dict
        this.handleQuery()
      } else {
        this.tableData = []
      }
    }
  }
}
</script>
